<template>
	<view class="">
		<view class="list">
			<form @submit="formSubmit" @reset="formReset">
				<view class="uni-form-item uni-column">
					<view class="acea-row row-middle row-between item border-b ">
						<view class="label label-m">
							服务类别
						</view>
						<view class="acea-row row-middle row-right item-r sanjiao-right" @click="openPicker('typeId')">
							<input class="input-r" type="text" placeholder="请选择服务类别"
								placeholder-class="placeholder-class" v-model="type" disabled />
						</view>
					</view>
				</view>
				<view class="uni-form-item uni-column">
					<view class="acea-row row-middle row-between item border-b ">
						<view class="label">
							标题
						</view>
						<view class="acea-row row-middle row-right item-r ">
							<input class="input-r mr30" type="text" placeholder="请输入标题"
								placeholder-class="placeholder-class" v-model="dataForm.title" />
						</view>
					</view>
				</view>
				<view class="uni-form-item uni-column">
					<view class="acea-row row-middle row-between item border-b ">
						<view class="label label-m">服务价格</view>
						<view class="acea-row row-middle row-right item-r small-ipt">
							<input type="number" placeholder="示例:500" v-model="dataForm.price"
								placeholder-class="placeholder-class" @input="fillTitle">
							<text>元</text>
						</view>
					</view>
				</view>
				<view class="uni-form-item uni-column">
					<view class="acea-row row-middle row-between item border-b ">
						<view class="label label-m">
							服务区域
						</view>
						<view class="acea-row row-middle row-right item-r sanjiao-right" @click="goServiceArea">
							<input class="input-r" type="text" placeholder="请选择服务区域"
								placeholder-class="placeholder-class" v-model="regionName" />
						</view>
					</view>
				</view>
				<!-- 服务特色 -->
				<view class="module coust">
					<!-- 	<view class="acea-row row-middle row-between">
						<view class="module-title">
							服务特色
						</view>
						<view class="add-advantage red-sanjiao-r" @click="addAd">
							没找到合适的？选择自定义
						</view>
					</view>
					<view class="acea-row advantage-list">
						<view class="itemBox" v-for="(item,index) in advantages" :key="index">
							<icon type="cancel" color="#000" size="14" @click="closeAdvantages(item,index)"
								class="close" />
							<view class="item" :class="advantageIds.indexOf(index)!=-1?'item-on':''"
								@click="advantageChecked(item,index)">{{item}}</view>
						</view>
					</view> -->
					<chooseKeywords title="服务特色" :advantages="advantages" type="3" :storeAdvantage="storeAdvantage"
						padding="0" :advantageIds="advantageIds" @storeAdvantage="val=>(storeAdvantage=val)"
						@advantageIds="val=>(advantageIds=val)" @advantages="val=>(advantages=val)" />
				</view>
				<view class="uni-form-item uni-column">
					<!-- 描述 -->
					<view class="module">
						<view class="module-title">
							描述
						</view>
						<view class="textacea-box">
							<textarea placeholder="请描述" v-model="dataForm.particulars"
								:maxlength="maxLength"></textarea>
							<view class="num-text">
								{{dataForm.particulars.length}}/{{maxLength}}
							</view>
						</view>
					</view>
				</view>
				<view class="uni-form-item uni-column">
					<view class="acea-row row-middle row-between item border-b ">
						<view class="label label-m">
							服务地址
						</view>
						<view class="acea-row row-middle row-right item-r address">
							<input type="text" placeholder="请输入/选择地址" v-model="dataForm.address">
							<image src="../static/images/location.png" mode="" @click="mapChooseLocation"></image>
						</view>
					</view>
				</view>
				<view class="uni-form-item uni-column">
					<!-- 联系人 -->
					<view class="acea-row row-middle row-between item ">
						<view class="label label-m">
							联系人
						</view>
						<view class="add-icon" @click="toPage('/pages/releases/addShopContact/addShopContact')">
							<image src="../static/images/add_icon.png" mode=""></image>
						</view>
					</view>
					<view class="item ">
						<chooseContact :list="contactList" :dataform="dataForm" @add="d=>contactList.push(d)"
							@del="toDel" />
					</view>
				</view>
				<view class="uni-form-item uni-column">
					<!-- 上传照片/视频 -->
					<view class="module">
						<view class="acea-row row-middle row-between">
							<view class="module-title label-m">
								上传图片/视频
							</view>
							<view class="example-text">
								图片示例
							</view>
						</view>
						<view class="example-text-l">
							请至少添加一张照片，图片越多审核越快
						</view>
						<view class="acea-row pictrue-list">
							<view class="acea-row row-column row-center-wrapper pictrue" v-for="item in PhotoList"
								:key="item.url">
								<image :src="item.url" mode="" v-if="item.type=='image'"></image>
								<video :src="item.url" mode="" v-else></video>
							</view>
							<view class="acea-row row-column row-center-wrapper pictrue" @click="uploadImg"
								v-if="PhotoList.length<3">
								<view class="upload-icon">
									<image src="../static/images/upload_icon.png" mode=""></image>
								</view>
								<view>添加照片/视频</view>
							</view>
						</view>
						<!-- <view class="acea-row row-center row-center add-more-picture">
							<view>添加更多照片</view>
							<view class="jiantou-b"></view>
						</view> -->
					</view>
				</view>

				<button class="submit-btn" form-type="submit">
					完成
				</button>
			</form>
		</view>
		<not-service-provider @close="closeApplyProvider" v-if="showProvider"></not-service-provider>
		<u-picker :show="pickerShow" :columns="columns" :defaultIndex="defaultIndex" :keyName="keyName"
			@confirm="pickerConfirm" @cancel="pickerShow = false"></u-picker>
		<serviceArea :filtrateArr="filtrateArr" ref="serviceArea" @area="handleArea" />
		<addKeyWord ref="addKeyWord" @addConfirm="addConfirm" />
	</view>
</template>

<script>
	import notServiceProvider from '../components/notServiceProvider/notServiceProvider.vue';
	import serviceArea from './area.vue'
	import {
		POST_TYPE
	} from '@/config/app.js';
	import {
		ServiceAdd,
		ServiceUpdate
	} from '@/api/service.js';

	import addKeyWord from '../components/addKeyWord/addKeyWord.vue'
	import chooseKeywords from '../components/chooseKeywords.vue'
	import chooseContact from '../components/chooseContact.vue'
	export default {
		components: {
			notServiceProvider,
			serviceArea,
			addKeyWord,
			chooseKeywords,
			chooseContact
		},
		props: {
			typeList: {
				type: Array,
				dafault: () => []
			},
			statsus: {
				type: Number,
				default: 0
			},
			item: {
				type: Object,
				default: () => {}
			},
			types:{
				default: Number,
				default: 0
			}
		},
		watch: {
			typeList(val) {
				console.log(val)
			},
			"item": {
				handler(val) {
					console.log(val);
					if (!val.characteristic) return
					this.dataForm = val;
					this.type = val.typeName
					this.regionName = val.area;
					if (val.contacts) {
						this.contactList = val.contacts && val.contacts.map(item => {
							return {
								id: item.contactId,
								status: item.open,
								type: item.contactType,
								username: item.contactName,
								phone: item.contactPhone,
								open: item.open,
								were: item.were
							}
						})
						console.log("this.contactList ", this.contactList)
					}

					console.log("this.contactList", this.contactList)
					val.characteristic && val.characteristic.replaceAll(',', '/').split('/').forEach((item,
						index) => {
						let ind = this.advantages.indexOf(item);
						if (ind == -1) {
							this.advantages.push(item)
							this.storeAdvantage.push(item)
							this.advantageIds.push(this.advantages.length - 1)
						} else {
							this.advantageIds.push(ind)
							this.storeAdvantage.push(this.advantages[ind])
						}

					})
					if (val.image && val.image.replaceAll(" ", "")) {
						this.PhotoList = val.image.split(',').map(item => {
							const type = item.substring(item.length - 3, item.length);
							return {
								url: item,
								type: ['png', 'jpg'].includes(type) ? 'image' : 'video'
							}
						})
					}


				},
				deep: true, // 深度监听
				immediate: true // 第一次改变就执行
			}
		},
		data() {
			return {
				filtrateArr: [{
					type: '区域'
				}],
				type: '', //服务类别中文
				pickerShow: false, //控制选择器开关
				defaultIndex: [], //选择器当前第一列显示索引
				keyName: '', //选择器列显示的内容
				pickerType: '',
				contactList: [],
				dataForm: {
					particulars: '',
					contacts: []
				},
				storeAdvantage: [],
				columns: [],
				showProvider: false,
				isWidth: 40,
				isLeft: 0,
				maxLength: 200,
				regionName: '',
				PhotoList: [],
				advantages: [], //加盟要求
				advantageIds: [],
				initArea: 0,
				cityInfo:{}
			};
		},
		mounted() {
			let that = this;
			// uni.$on('contact', function(data) {
			// 	if (that.contactList.findIndex(item => item.phone == data.phone) == -1) {
			// 		that.contactList.push({
			// 			...data,
			// 			status: 0
			// 		});
			// 	}
			// })
			// uni.$on('initContact', function(data) {
			// 	if (that.contactList.length < 1) {
			// 		that.contactList.push(data)
			// 	}
			// })
			that.$set(that.dataForm, 'address', that.$address)
			that.$set(that.dataForm, 'latitude', this.$location.latitude)
			that.$set(that.dataForm, 'longitude', this.$location.longitude)
			getApp().globalData.initContact()
			this.getBusiness({
				longitude: that.dataForm.longitude,
				latitude: that.dataForm.latitude,
			})
		},
		methods: {
			getBusiness(location,callabck) {
				let that = this;
				getApp().globalData.getBusinessList(location).then(res => {
					if (res.code == 200) {
						
						that.cityInfo = res.data;
						console.log('res',that.cityInfo)
						callabck&&callabck(that.cityInfo);
						// that.dataform.province = res.data.province;
						// that.dataform.city = res.data.city;
						// that.dataform.district = res.data.district;
						// that.dataform.businessName = res.data.businessName;
						// that.dataform.businessCircle = res.data.businessId;
						// that.fillTilte()
					}
				});
			},
			//添加店铺优势
			addAd() {
				this.$refs.addKeyWord.popupShow = true
			},
			toDel(index, info, callback) {
				if (info) {
					this.contactList.splice(index, 1, info);
				} else {
					this.contactList.splice(index, 1);
				}
				callback && callback();
			},
			addConfirm(e) {
				this.advantages = this.advantages.concat(e)
			},
			//删除标签
			closeAdvantages(item, index) {
				this.advantages.splice(index, 1)
				if (this.advantageIds.indexOf(index) != -1) {
					let idx = this.advantageIds.indexOf(index)
					this.advantageIds.splice(idx, 1);
				}
			},
			advantageChecked(item, index) {
				if (this.advantageIds.indexOf(index) != -1) {
					let idx = this.advantageIds.indexOf(index)
					this.advantageIds.splice(idx, 1);
				} else {
					this.advantageIds.push(index);
				}
			},
			//删除联系人
			deleteContact(index) {
				this.contactList.splice(index, 1)
			},
			//自动填充标题
			fillTitle() {

				if (this.dataForm.typeId && this.dataForm.price) {
					this.dataForm.title = this.dataForm.price + '元求' + this.type
				}
			},
			//去选择服务区域
			goServiceArea() {
				this.$refs.serviceArea.filtrateShow = true
			},
			closeApplyProvider() {
				this.showProvider = false
			},
			//打开选择器
			openPicker(params) { //params为表单属性
				this.pickerType = params
				switch (params) {
					case 'typeId':
						this.columns = [this.typeList];
						this.keyName = 'name';
						this.defaultIndex = [0];
						break;
					default:
						this.columns = []
				}
				this.pickerShow = true;
			},
			//选择器点击确认
			pickerConfirm(e) {
				this.dataForm[this.pickerType] = e.value[0].id;
				this.type = e.value[0].name;
				this.pickerShow = false;
				this.fillTitle()
			},
			//表单提交
			formSubmit() {
				let that = this;
				that.dataForm.contacts = this.contactList;
				let images = this.PhotoList.map(item => {
					return item.url
				})
				this.dataForm.statsus = this.statsus;
				// this.dataForm.characteristic = this.advantageIds.map(item => this.advantages[item]).join(',');
				this.dataForm.characteristic = this.storeAdvantage.join('/')
				if (images.length > 0) {
					this.dataForm.image = images.join(','); //处理图片数据
				}

				if (!this.dataForm.typeId) return that.$util.Tips({
					title: '请输入服务类别'
				});
				if (!this.dataForm.characteristic) return that.$util.Tips({
					title: '请输入服务特色'
				});
				if (!this.dataForm.price) return that.$util.Tips({
					title: '请输入服务价格'
				});
				if (!this.dataForm.area) return that.$util.Tips({
					title: '请选择服务区域'
				});
				if (!this.dataForm.address) return that.$util.Tips({
					title: '请选择/输入服务地址'
				});
				if (!this.dataForm.contacts.length > 0) return that.$util.Tips({
					title: '请添加至少一位联系人'
				});
				// if (!this.dataForm.image) return that.$util.Tips({
				// 	title: '请添加至少一张照片/视频'
				// });
				this.handleConfrim()
			},
			async handleConfrim() {
				try {
					this.dataForm.city = this.$city;
					if(this.dataForm.type!=0 && this.dataForm.type!=1 ){
						this.dataForm.type= this.types
					}
					this.dataForm.contacts = this.contactList.map(item => {
						const {
							id,
							type,
							open,
							were
						} = item;
						return {
							contactId: id,
							identity: type,
							open,
							were
						}
					})
					if(!this.dataForm.id){
						this.dataForm.province = this.$cityCode[0];
						this.dataForm.city = this.$city;
						this.dataForm.district = this.$cityCode[2]
						if(this.cityInfo.street){
							this.dataForm.street = this.cityInfo.street
						}
					}
					let res = this.dataForm.id ? await ServiceUpdate(this.dataForm) : await ServiceAdd(this.dataForm);
					uni.showToast({
						title: '成功',
						icon: 'none'
					})
					uni.navigateTo({
						url: '/pages/releases/business/business'
					})
				} catch (e) {
					console.log("e", e)
					//TODO handle the exception
					uni.showToast({
						title: '发布失败',
						icon: 'error'
					})
				}
			},
			//选取地址
			mapChooseLocation() {
				uni.chooseLocation({
					success: (res) => {
						this.$set(this.dataForm, 'address', res.address);
						this.$set(this.dataForm, 'latitude', res.latitude);
						this.$set(this.dataForm, 'longitude', res.longitude);
						this.getBusiness({
							latitude:res.latitude,
							longitude: res.longitude
						},data=>{
							this.dataForm.province = data.province;
							this.dataForm.city = data.city;
							this.dataForm.district = data.district;
							this.dataForm.street = data.street;
						})
					},
				})
			},
			//跳转页面
			toPage(url) {
				uni.navigateTo({
					url
				})
			},
			//服务区域
			handleArea(areaInfo) {
				if (this.item.id) {

				}
				this.dataForm.city = areaInfo.cityId;
				this.dataForm.area = areaInfo.districtIds;
				this.regionName = areaInfo.regionName;
			},
			//上传照片
			uploadImg() {
				uni.showActionSheet({
					title: '选择上传类型',
					itemList: ['图片', '视频'],
					success: res => {
						if (res.tapIndex == 0) {
							this.chooseImages();
						} else {
							this.chooseVideo();
						}
					}
				});
			},
			//选择照片
			chooseImages() {
				let that = this;
				that.$util.uploadImageOne({
					url: 'upload/image',
					count: 5,
					name: 'multipart',
					model: "user",
					pid: 0
				}, function(res) {
					console.log(res)
					that.PhotoList.push({
						url: res.data.url,
						type: 'image'
					})
				});
			},
			//选择视频
			chooseVideo() {
				let that = this;
				that.$util.uploadVideo({
					url: 'upload/image',
					name: 'multipart',
					model: "user",
					pid: 0
				}, function(res) {
					that.PhotoList.push({
						url: res.data.url,
						type: 'video'
					})
				});
			},
		}
	}
</script>

<style lang="scss" scoped>
	@import '/static/css/releaseForm.css';
</style>